package com.taxi.driver.module.main.mine.help.feedback;

import com.qianxx.network.RequestError;
import com.qianxx.utils.RxUtil;
import com.taxi.driver.R;
import com.taxi.driver.common.BasePresenter;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.module.vo.FeedbackVO;

import javax.inject.Inject;

public class FeedbackPresenter extends BasePresenter implements FeedbackContract.Presenter {
    UserRepository mUserRepository;
    FeedbackContract.View mView;

    @Inject
    public FeedbackPresenter(UserRepository userRepository,FeedbackContract.View view) {
        mUserRepository = userRepository;
        mView = view;
    }

    @Override
    public void reqFeedbacks(int nowPage) {
        mUserRepository.getFeedbacks(nowPage)
                .flatMapIterable(entities -> entities)
                .map(FeedbackVO::createFrom)
                .toList()
                .compose(RxUtil.applySchedulers())
                .subscribe(vos -> {
                    mView.showFeedbacks(vos);
                }, ex -> {
                    showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                });
    }

    @Override
    public void addFeedback(String content) {
        mUserRepository.addFeedback(content,content)
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(false))
                .doAfterTerminate(() -> mView.hideLoadingView())
                .subscribe(vos -> {
                    mView.addFeedbackSucc();
                }, ex -> {
                    showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                    Throwable throwable = ex.getCause();
                    if (throwable instanceof RequestError) {
                        RequestError error = ((RequestError) throwable);
                        mView.addFeedbackFail(error.getErrCode(), error.getMessage());
                    }
                });
    }
}
